package com.tucc.hello.sort;

/**
 * @author tucc
 * @description todo
 * @package com.tucc.hello.sort
 * @date 2021/5/27
 **/
public class BinarySearch {

    public static int binarySearch(int[] arr, int aim) {
        return binarySearch(arr, 0, arr.length - 1, aim);
    }

    public static int binarySearch(int[] arr, int left, int right, int aim) {
        if (left > right) {
            return -1;
        }
        if (left == right) {
            return arr[left] == aim ? left : -1;
        }
        int mid = (left + right) / 2;
        if (aim == arr[mid]) {
            return mid;
        }
        if (aim > arr[mid]) {
            return binarySearch(arr, mid + 1, right, aim);
        } else {
            return binarySearch(arr, left, mid - 1, aim);
        }
    }

    public static int binarySearch2(int[] arr, int aim) {
        int left = 0;
        int right = arr.length - 1;
        while (left <= right) {
            if (left == right) {
                return aim == arr[left] ? left : -1;
            }
            int mid = (left + right) / 2;
            if (arr[mid] == aim) {
                return mid;
            }
            if (mid < aim) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }

        return -1;
    }

    public static void main(String[] args) {
        int[] arr = {1, 4, 5, 8, 10, 18, 24};
        System.out.println(binarySearch(arr, 18));

        System.out.println(binarySearch2(arr, 18));
    }
}
